package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.apis.article.IArticleClient;
import com.heima.common.aliyun.GreenImageScan;
import com.heima.common.aliyun.GreenTextScan;
import com.heima.common.constants.WmNewsMessageConstants;
import com.heima.common.tess4j.Tess4jClient;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmSensitive;
import com.heima.utils.common.SensitiveWordUtil;
import com.heima.wemedia.builder.ArticleDtoBuilder;
import com.heima.wemedia.mapper.WmChannelMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmSensitiveMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Transactional
@Slf4j
public class WmNewsAutoScanServiceImpl implements WmNewsAutoScanService {
    @Autowired
    private WmNewsMapper wmNewsMapper;
    @Autowired
    private GreenTextScan greenTextScan;
    @Autowired
    private GreenImageScan greenImageScan;
    @Autowired
    private FileStorageService fileStorageService;
    @Autowired
    private IArticleClient articleClient;

    @Autowired
    private WmChannelMapper wmChannelMapper;

    @Autowired
    private WmUserMapper wmUserMapper;
    @Autowired
    private WmSensitiveMapper wmSensitiveMapper;
    @Autowired
    private Tess4jClient tess4jClient;
    @Autowired
    private KafkaTemplate kafkaTemplate;

    /**
     * 自媒体文章审核
     * @param id
     */
    @Override
    @Async
    @GlobalTransactional
    public void autoScanWmNews(Integer id) {
        //1.查询自媒体文章
        WmNews wmNews = wmNewsMapper.selectById(id);
        if (wmNews == null){
            throw new RuntimeException("WmNewsAutoScanServiceImpl-文章不存在");
        }
        //只有当状态为提交未审核的时候才执行
        if (wmNews.getStatus().equals(WmNews.Status.SUBMIT.getCode())){
            //从内容中提取纯文本内容和图片
            Map<String,Object> textAndImages =  handleTextAndImages(wmNews);

            //自管理的敏感词过滤
            boolean isSensitive = handleSensitiveScan((String)textAndImages.get("content"), wmNews);;
            if (!isSensitive){
                return;
            }
                    //2.审核文本内容 阿里云接口
            Boolean isTextScan = handleTextScan(textAndImages.get("content"),wmNews);
            //如果返回值为false那么就直接return
            if (!isTextScan){
                return;
            }
            //3.审核图片 阿里云接口
            Boolean isImageScan= handleImageScan((List<String>) textAndImages.get("images"),wmNews);
            if (!isImageScan){
                return;
            }
            //4.审核成功，保存app端的相关文章数据
            ResponseResult  responseResult = saveAppArticle(wmNews);

            if (!responseResult.getCode().equals(200)){
                //代表审核失败
                throw new RuntimeException("WmNewsAutoScanServiceImpl-文章审核，保存app端相关文章数据失败");
            }
//            //=====================自定义异常=============================
//            int a = 1/0;
//            //==========================================================
            //回填article_id
            wmNews.setArticleId((Long) responseResult.getData());
            updateWmNews(wmNews,WmNews.Status.PUBLISHED,"审核成功");
            //发送kafkaTemplate
            Map<String, Object> map = new HashMap<>();
            map.put("articleId",wmNews.getArticleId());
            map.put("enable",wmNews.getEnable());
            kafkaTemplate.send(WmNewsMessageConstants.WM_NEWS_UP_OR_DOWN_TOPIC,JSON.toJSONString(map));
        }
    }

    /**
     * 自管理的敏感词过滤
     * @param content
     * @param wmNews
     * @return
     */
    private boolean handleSensitiveScan(String content, WmNews wmNews) {
        boolean flag = Boolean.TRUE;
        //获取所有的敏感词
        List<WmSensitive> wmSensitives = wmSensitiveMapper.selectList(Wrappers.<WmSensitive>lambdaQuery().select(WmSensitive::getSensitives));
        //用map方法进行遍历获得每一个敏感词
        List<String> sensitiveList = wmSensitives.stream().map(WmSensitive::getSensitives).collect(Collectors.toList());
        //初始化敏感词词库
        SensitiveWordUtil.initMap(sensitiveList);
        //查看文章中是否包含敏感词
        Map<String, Integer> map = SensitiveWordUtil.matchWords(content);
        if (map.size() > 0 ){
            updateWmNews(wmNews,WmNews.Status.FAIL,"当前文章中存在违规内容"+map);
            flag = Boolean.FALSE;
        }
        return flag;


    }

    /**
     * 保存文章数据
     * @param wmNews
     * @return
     */
    public ResponseResult saveAppArticle(WmNews wmNews) {
//        ArticleDto dto = new ArticleDto();
//        //属性拷贝
//        BeanUtils.copyProperties(wmNews,dto);
//        //文章的布局
//        dto.setLayout(wmNews.getType());
//        //频道
//        WmChannel wmChannel = wmChannelMapper.selectById(wmNews.getChannelId());
//        //拷贝频道的名字
//        if (wmChannel != null){
//            dto.setChannelName(wmChannel.getName());
//        }
//        //作者的名字
//        WmUser wmUser = wmUserMapper.selectById(wmNews.getUserId());
//        if (wmUser != null){
//            dto.setAuthorName(wmUser.getName());
//        }
//        //设置文章id
//        if (wmNews.getArticleId() !=null){
//            dto.setId(wmNews.getArticleId());
//        }
//        //创建时间
//        dto.setCreatedTime(new Date());
        ArticleDto articleDto = new ArticleDtoBuilder(wmNews,wmChannelMapper,wmUserMapper)
                .buildBeanCopy()
                .buildAuthor()
                .buildBasic()
                .buildChannel()
                .builder();
        //远程调用save方法进行保存
        ResponseResult responseResult = articleClient.saveArticle(articleDto);
        return responseResult;
    }

    /**
     * 审核内容图片和封面图片
     * @param images
     * @param wmNews
     * @return
     */
    private Boolean handleImageScan(List<String> images, WmNews wmNews){
        boolean flag = Boolean.TRUE;
        //首先判断图片是否为空
        if (images ==null || images.size() == 0){
            return flag;
        }
        //对图片去重
        images = images.stream().distinct().collect(Collectors.toList());
        //创建一个集合来存储下载的图片地址
        List<byte[]> imageList = new ArrayList<>();
        try {
            //下载图片
            for (String image : images) {
                byte[] bytes = fileStorageService.downLoadFile(image);
                //图片识别文字审核
                //从byte[]转换为butteredImage
                ByteArrayInputStream in = new ByteArrayInputStream(bytes);
                BufferedImage imageFile = ImageIO.read(in);
                //识别图片的文字
                String result = tess4jClient.doOCR(imageFile);
                //审核是否包含自管理的敏感词
                boolean isSensitive = handleSensitiveScan(result, wmNews);
                if(!isSensitive){
                    return isSensitive;
                }
                //图片识别文字审核---end-----

                imageList.add(bytes);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            //审核图片
            Map map = greenImageScan.imageScan(imageList);
            if (map != null)
            if (("block").equals(map.get("suggestion"))){
                flag = false;
                updateWmNews(wmNews, WmNews.Status.FAIL, "当前文章中存在违规内容");
            }
            if (("review").equals(map.get("suggestion"))){
                flag = false;
                updateWmNews(wmNews, WmNews.Status.ADMIN_AUTH, "当前文章中存在违规内容");
            }
        } catch (Exception e) {
            flag= Boolean.FALSE;
            e.printStackTrace();
        }

        return flag;
    }

    /**
     * 审核文本内容
     * @param content
     * @param wmNews
     * @return
     */
    private Boolean handleTextScan(Object content, WmNews wmNews) {
        boolean flag = Boolean.TRUE;
        try {
            Map map = greenTextScan.greeTextScan(wmNews.getTitle() + "-" + content);
            if (map != null){
                //审核失败
                if (("block").equals(map.get("suggestion"))){
                    flag = Boolean.FALSE;
                    //返回状态码2和违规信息
                    updateWmNews(wmNews, WmNews.Status.FAIL, "文章审核失败,文章中包含违规信息");
                }
                //不确定信息,需要人工介入
                if (("review").equals(map.get("suggestion"))){
                    flag = Boolean.FALSE;
                    updateWmNews(wmNews, WmNews.Status.ADMIN_AUTH, "文章内容不确定,需要人工介入");
                }
            }
        } catch (Exception e) {
            flag = Boolean.FALSE;
            e.printStackTrace();
        }
        //没有文字内容直接返回true,或者审核成功也返回true
        return flag;

    }

    private void updateWmNews(WmNews wmNews, WmNews.Status fail, String reason) {
        wmNews.setStatus(fail.getCode());
        wmNews.setReason(reason);
        wmNewsMapper.updateById(wmNews);
    }

    /**
     * 1.从自媒体文章的内容中提取文本和图片
     * 2.提取文章的封面图片
     * @param wmNews
     * @return
     */
    private Map<String, Object> handleTextAndImages(WmNews wmNews) {
        //创建一个StringBuilder存储纯文本
        StringBuilder sb = new StringBuilder();
        //创建一个集合来存储图片
        List<String> images = new ArrayList<>();
        //1.从自媒体中提取文字
        if (StringUtils.isNotBlank(wmNews.getContent())){
            List<Map> maps = JSON.parseArray(wmNews.getContent(), Map.class);
            for (Map map : maps) {
                if (("text").equals(map.get("type"))){
                    //说明是文字,用StringBuilder来存储
                    sb.append(map.get("value"));
                }
                if (("image").equals(map.get("type"))){
                    //说明是图片,用List来存储
                    images.add(map.get("value").toString());
                }
            }
        }
        //2.提取封面图片
        //2.1首先判断图片是否为空
        if (StringUtils.isNotBlank(wmNews.getImages())){
            //如果有多张图,用split切割一下
            String[] split = wmNews.getImages().split(",");
            images.addAll(Arrays.asList(split));
        }
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("content",sb.toString());
        resultMap.put("images",images);
        return resultMap;
//        //存储纯文本内容
//        StringBuilder stringBuilder = new StringBuilder();
//
//        //存储图片内容
//        List<String> images = new ArrayList<>();
//        //1.从自媒体文章的内容中提取文本和图片
//        if (StringUtils.isNotBlank(wmNews.getContent())){
//            List<Map> maps = JSONArray.parseArray(wmNews.getContent(), Map.class);
//            for (Map map : maps) {
//                if (map.get("type").equals("text")){
//                    stringBuilder.append(map.get("value"));
//                }
//                if (map.get("type").equals("image")){
//                    images.add((String) map.get("value"));
//                }
//            }
//        }
//        //2.提取文章的封面图片
//        if (StringUtils.isNotBlank(wmNews.getImages())){
//            String[] split = wmNews.getImages().split(",");
//            images.addAll(Arrays.asList(split));
//        }
//        Map<String,Object> resultMap = new HashMap<>();
//        resultMap.put("content",stringBuilder.toString());
//        resultMap.put("images",images);
//        return resultMap;
    }
}
